package com.weifly.weistock.record;

import com.weifly.weistock.record.bo.AbstractRecordBO;
import com.weifly.weistock.record.bo.RecordPair;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 工具类
 *
 * @author weifly
 * @since 2020/01/16
 */
public class RecordUtils {

    public static void sortRecordList(List<? extends AbstractRecordBO> recordList){
        recordList.sort((r1, r2) ->{
            int compareValue = r1.getDate().compareTo(r2.getDate());
            if(compareValue==0){
                // 日期相同，比较时间
                compareValue = r1.getTime().compareTo(r2.getTime());
                if(compareValue==0){
                    // 时间相同，比较委托号
                    compareValue = r1.getEntrustCode().compareTo(r2.getEntrustCode());
                }
            }
            return compareValue;
        });
    }

    public static void clearRecordPair(List<? extends AbstractRecordBO> recordList){
        for(AbstractRecordBO record : recordList){
            if(record.getPairList()!=null){
                record.getPairList().clear();
            }
            record.setDiffAmount(null);
        }
    }

    public static String makePairAttr(List<RecordPair> pairList, int tradeNumber){
        if(pairList==null || pairList.isEmpty()){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<pairList.size();i++){
            RecordPair pair = pairList.get(i);
            // 输出index
            if(pair.getNumber()==tradeNumber){
                sb.append(pair.getIndex());
            }else{
                sb.append(pair.getIndex());
                if(pair.getNumber()>1){
                    sb.append("(").append(pair.getNumber()).append(")");
                }
            }
            // 输出分隔符
            if(i<pairList.size()-1){
                sb.append(",");
            }
        }
        return sb.toString();
    }

    public static List<RecordPair> parsePairAttr(String pairAttr, int tradeNumber){
        if(StringUtils.isBlank(pairAttr)){
            return null;
        }
        List<RecordPair> pairList = new ArrayList<>();
        String[] parts = pairAttr.split(",");
        for(String p : parts){
            RecordPair pair = new RecordPair();
            if(p.indexOf("(")==-1){
                pair.setIndex(Integer.parseInt(p));
                pair.setNumber(tradeNumber);
            }else{
                int startIdx = p.indexOf("(");
                int endIdx = p.indexOf(")");
                pair.setIndex(Integer.parseInt(p.substring(0, startIdx)));
                pair.setNumber(Integer.parseInt(p.substring(startIdx+1, endIdx)));
            }
            pairList.add(pair);
        }
        return pairList;
    }
}